package com.qiall.gateway.controller;

import com.alibaba.fastjson.JSON;
import com.qiall.assertutil.Assert;
import com.qiall.gateway.controller.websocket.DataKafkaQueue;
import com.qiall.gateway.controller.websocket.Protocol;
import com.qiall.gateway.controller.websocket.SessionPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;


@Slf4j
@ServerEndpoint(value = "/socketMessage")
@Component
public class WebSocketController {


    private static DataKafkaQueue dataKafkaQueue;

    @Autowired
    public void setDataKafkaQueue(DataKafkaQueue dataKafkaQueue){
        WebSocketController.dataKafkaQueue=dataKafkaQueue;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        SessionPool.addSession(session);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        SessionPool.remove(session.getId());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        String sessionId = session.getId();
        try{

            Protocol protocol= JSON.parseObject(message,Protocol.class);
            Assert.notNull(protocol.getCommand(),"command is null");
            protocol.setSessionId(sessionId);
            dataKafkaQueue.sedSocketMessage(protocol);
        }
        catch (Exception e){
            log.error("message is [{}],error message is [{}]",message,e.getMessage());
        }

    }

    @OnError
    public void onError(Session session, Throwable error) {

        // 如果ping不到则删除会话
        ByteBuffer byteBuffer = ByteBuffer.wrap("ping".getBytes(StandardCharsets.UTF_8));
        try {
            log.error(error.getMessage());
            session.getBasicRemote().sendPing(byteBuffer);
        } catch (IOException e) {
            e.printStackTrace();
            SessionPool.remove(session.getId());
            log.error("session id is [{}] removed", session.getId());
        }
    }

}
